#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <cstring>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "UnCopy.hpp"
#include "Log.hpp"
#include "Commen.hpp"
#include "InetAddress.hpp"
#include "ThreadPool.hpp"

static const uint16_t default_port = 9090;
static const int default_fd = -1;
static const int default_buffer_size = 1024;

using task_t = std::function<void()>;

class UdpServer : public UnCopy
{
public:
    UdpServer(uint16_t port = default_port)
        : _port(port), _socket_fd(default_fd)
    {
        pthread_mutex_init(&_user_mutex, nullptr);
        init();
    }
    
    void init()
    {
        // 1.创建socket
        _socket_fd = socket(AF_INET, SOCK_DGRAM, 0); 
        if(_socket_fd < 0)
        {
            log.message(FATAL, "socket error, %d: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        log.message(INFO, "socket success, socket fd: %d", _socket_fd);

        // 2.填写本端网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 3.绑定 网络信息sockaddr 与 文件信息socket
        int n = bind(_socket_fd, (struct sockaddr*)&local, sizeof(local));
        if(n != 0)
        {
            log.message(FATAL, "bind error, %d: %s\n", errno, strerror(errno));
            exit(BIND_ERR);
        }

        ThreadPool<task_t>::getInstance()->start();
        log.message(INFO, "udp server ready...");

        // 4.填写对端网络信息，服务端在接收时确定（输出型参数）
    }

    void start()
    {
        log.message(INFO, "udp server start...");
        char buffer[default_buffer_size];
        while(true)
        {
            struct sockaddr_in peer; //对端信息
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_socket_fd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                buffer[n] = '\0';
                addOnlineUser(InetAddress(peer));
                task_t task = std::bind(&UdpServer::route, this, _socket_fd, buffer); //绑定参数
                ThreadPool<task_t>::getInstance()->submit(task);
            }
        }
    }

    void addOnlineUser(InetAddress address)
    {
        LockGuard lock(&_user_mutex);
        for(auto& user : _online_user)
        {
            if(address == user) return;
        }
        _online_user.push_back(address);
        log.message(INFO, "add online user [%s:%d]...", address.getIp().c_str(), address.getPort());
    }

    void route(int socket_fd, const std::string& message)
    {
        for(auto& user : _online_user)
        {
            sendto(socket_fd, message.c_str(), message.size(), 0, 
                (struct sockaddr*)&user.getAddress(), sizeof(user.getAddress()));
        }
        log.message(INFO, "\"%s\" send done...", message.c_str());
    }

    ~UdpServer()
    {
        pthread_mutex_destroy(&_user_mutex);
    }
private:
    uint16_t _port;
    int _socket_fd;
    std::vector<InetAddress> _online_user;
    pthread_mutex_t _user_mutex;
};